package com.project.utils;

import com.project.bean.system.TblDeptBean;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author : Mr.Yan
 * @program : com.project.utils
 * @create : 2020/03/30
 * @description : 将部门数据变成树
 */
public class DeptTreeUtil {

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @return String
     */
    public static List<TblDeptBean> getChildPerms(List<TblDeptBean> list, String parentDeptId) {
        List<TblDeptBean> returnList = new ArrayList<TblDeptBean>();
        for (Iterator<TblDeptBean> iterator = list.iterator(); iterator.hasNext(); ) {
            TblDeptBean t = (TblDeptBean) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getDeptId().equals(parentDeptId)) {
                // 第一层
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private static void recursionFn(List<TblDeptBean> list, TblDeptBean t) {
        if (hasChild(list, t)) {
            // 得到子节点列表
            List<TblDeptBean> childList = getChildList(list, t);
            t.setChildren(childList);
            for (TblDeptBean tChild : childList) {
                if (hasChild(list, tChild)) {
                    // 判断是否有子节点
                    Iterator<TblDeptBean> it = childList.iterator();
                    while (it.hasNext()) {
                        TblDeptBean n = (TblDeptBean) it.next();
                        recursionFn(list, n);
                    }
                }
            }
        }
    }

    /**
     * 判断是否有子节点
     */
    private static boolean hasChild(List<TblDeptBean> list, TblDeptBean t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 得到子节点列表
     */
    private static List<TblDeptBean> getChildList(List<TblDeptBean> list, TblDeptBean t) {
        List<TblDeptBean> tlist = new ArrayList<TblDeptBean>();
        Iterator<TblDeptBean> it = list.iterator();
        while (it.hasNext()) {
            TblDeptBean n = (TblDeptBean) it.next();
            if (n.getParentDeptId().equals(t.getDeptId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }


}
